package database;

import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletContextEvent;

import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;

public class Connect {
	public static String url;
	public static String username;
	public static String password;
	public static String driver;
	public static DataSource ds;
	public static void initConnection(ServletContextEvent evt)
	{
        url = evt.getServletContext().getInitParameter("database.url");
        username = evt.getServletContext().getInitParameter("database.username");
        password = evt.getServletContext().getInitParameter("database.password");
        driver = evt.getServletContext().getInitParameter("database.driver");
        PoolProperties p = new PoolProperties();
        p.setUrl(url);
        p.setDriverClassName(driver);
        p.setUsername(username);
        p.setPassword(password);
        p.setJmxEnabled(true);
        p.setTestWhileIdle(false);
        p.setTestOnBorrow(true);
        p.setValidationQuery("SELECT 1");
        p.setTestOnReturn(false);
        p.setValidationInterval(30000);
        p.setTimeBetweenEvictionRunsMillis(30000);
        p.setMaxActive(100);
        p.setInitialSize(10);
        p.setMaxWait(10000);
        p.setRemoveAbandonedTimeout(60);
        p.setMinEvictableIdleTimeMillis(30000);
        p.setMinIdle(10);
        p.setLogAbandoned(true);
        p.setRemoveAbandoned(true);
        p.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
        ds = new DataSource();
        ds.setPoolProperties(p); 
		return;
	}
	
	public static Connection getConnection() throws SQLException
	{
		return ds.getConnection();
	}
	
	/*public static Connection getConnection()
	{
		//TODO get one of the static connections we configured and synchronize
		Connection con;
        try {
			Class.forName(driver);
			con = DriverManager.getConnection(url, username, password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
		return con;
	}
	*/
	
	
}

